package com.huike.business.service.impl;


import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.business.mapper.TbBusinessTrackRecordMapper;
import com.huike.business.service.ITbBusinessTrackRecordService;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.vo.ClueTrackRecordVo;
import com.huike.clues.mapper.TbClueTrackRecordMapper;
import com.huike.clues.service.ISysDictDataService;
import com.huike.common.utils.DateUtils;
import com.huike.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商机跟进记录Service业务层处理
 * 
 * @author wgl
 * @date 2021-04-28
 */
@Service
@Transactional
public class TbBusinessTrackRecordServiceImpl implements ITbBusinessTrackRecordService {

    @Autowired
    private TbBusinessTrackRecordMapper recordMapper;

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private ISysDictDataService dataService;

    @Override
    public int save(BusinessTrackVo businessTrackVo) {
        String username = SecurityUtils.getUsername();
        businessTrackVo.setCreateBy(username);
        businessTrackVo.setCreateTime(DateUtils.getNowDate());
        List<BusinessTrackVo> search = search(businessTrackVo.getBusinessId());
        TbBusiness tbBusiness = businessMapper.selectTbBusinessById(businessTrackVo.getBusinessId());
        if(search.size()>0){
            // BeanUtils拷贝工具类，可以把一个对象拷贝到另一个对象上
            BeanUtils.copyProperties(businessTrackVo,tbBusiness);
            tbBusiness.setId(businessTrackVo.getBusinessId());
            businessMapper.updateTbBusiness(tbBusiness);
        }
        return recordMapper.save(businessTrackVo);
    }

    @Override
    public List<BusinessTrackVo> search(Long businessId) {
        String username = SecurityUtils.getUsername();
        TbBusiness business = businessMapper.selectTbBusinessById(businessId);
        List<BusinessTrackVo> voList = recordMapper.search(username, businessId);
        List<BusinessTrackVo> list = voList.stream().map((vo)->{
            BeanUtils.copyProperties(business,vo);
            String[] strings = vo.getKeyItems().split(",");
            List<String> keys = vo.getKeys();
            for (String string : strings) {
                String point = dataService.selectDictLabel("communication_point", string);
                keys.add(point);
            }
            return vo;
        }).collect(Collectors.toList());
        return list;
    }
}
